const _ = require('lodash');
const prefix = '/api/spider';
module.exports = (app) => {
  const {router, middleware, model, spider} = app;

  const orderColumns = ['num_new', 'num_open', 'num_watch', 'num_active'];

  /** 所有的平台 */
  router.get(prefix + '/platforms', middleware.api(), async ctx => {
    ctx.body = await spider.Platform.findAll(
        {raw: true, where: {disabled: false}});
  });

  /** 单个平台的分类数据 */
  router.get(prefix + '/platform/:id(\\d+)/:date', middleware.api(),
      async ctx => {
        const platformId = parseInt(ctx.params.id);

        const where = {
          type_id: {
            [app.Sequelize.Op.not]: 1,
          },
          created_at: new Date(parseInt(ctx.params.date)),
        };
        const include = [{model: spider.Type}];
        // 所有平台
        if (platformId === 0) {
          include[1] = {model: spider.Platform, where: {disabled: false}};
        }
        //单一平台
        else {
          const platform = await spider.Platform.count(
              {where: {id: ctx.params.id, disabled: false}});
          if (!platform)
            return ctx.helper.error('不存在的平台');

          where.platform_id = platformId;
        }

        let order = ctx.query.order === 'descending' ? 'desc' : 'asc';
        let prop = orderColumns.indexOf(ctx.query.prop) === -1 ?
            orderColumns[0] : ctx.query.prop;

        if (platformId > 0 && prop === 'num_active') {
          prop = 'rank';
          if (order === 'desc')
            order = 'asc';
        }

        let page = parseInt(ctx.query.page);
        if (!(page > 0))
          page = 0;

        const [total, list] = await Promise.all([
          spider.TypeData.count({where}),
          spider.TypeData.findAll({
            where,
            order: [[prop, order]],
            limit: 20,
            offset: page * 20,
            include,
          }),
        ]);

        ctx.body = {total, list, page: page + 1};
      });

  /** 搜索分类 */
  router.get(prefix + '/types', middleware.api(2), async ctx => {
    const {Platform, Type, PlatformType} = spider;
    const where = {};
    let {id, search} = ctx.query;
    if (!_.isEmpty(search))
      where.name = {[ctx.app.Sequelize.Op.like]: '%' + search + '%'};
    else if (!_.isEmpty(id))
      where.id = {[ctx.app.Sequelize.Op.in]: id.split(',')};
    else
      return ctx.body = [];
    let result;
    if (id) {
      result = await PlatformType.findAll({
        where,
        include: [{model: Type}],
      });
    } else {
      result = await PlatformType.findAll({
        include: [
          {model: Platform},
          {model: Type, order: [['name', 'asc']], where},
        ],
      });
      result = result.map(item => {
        return {
          id: item.id,
          type: item.type,
          platform: item.platform,
        };
      });
    }
    ctx.body = result;
  });
};